{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "import tensorflow as tf\r\n",
    "from tensorflow.examples.tutorials.mnist import input_data\r\n",
    "tf.compat.v1.disable_eager_execution()\r\n",
    "#下载数据集\r\n",
    "mnist = input_data.read_data_sets('MNIST_data',one_hot=True)\r\n",
    "#每个批次的大小\r\n",
    "batch_size = 100\r\n",
    "#计算一共有多个批次  //batch_size\r\n",
    "n_batch = mnist.train.num_examples\r\n",
    "x = tf.compat.v1.placeholder(tf.float32,[None,784])\r\n",
    "#0-9 10个数字\r\n",
    "y = tf.compat.v1.placeholder(tf.float32,[None,10])\r\n",
    "#创建一个简单的神经网络\r\n",
    "W = tf.Variable(tf.zeros([784,10]))\r\n",
    "b = tf.Variable(tf.zeros([10]))\r\n",
    "\r\n",
    "prediction = tf.nn.softmax(tf.matmul(x,W)+b)\r\n",
    "#二次代阶函数\r\n",
    "# loss = tf.reduce_mean(tf.square(y-prediction))\r\n",
    "#交叉熵代价函数\r\n",
    "loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))\r\n",
    "#使用梯度下降法\r\n",
    "# train_step = train_step = tf.compat.v1.train.GradientDescentOptimizer(0.2).minimize(loss)\r\n",
    "train_step = tf.compat.v1.train.AdamOptimizer(1e-3).minimize(loss)\r\n",
    "#初始化变量\r\n",
    "init = tf.compat.v1.global_variables_initializer()\r\n",
    "#\r\n",
    "correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))\r\n",
    "#求准确率\r\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\r\n",
    "\r\n",
    "with tf.compat.v1.Session() as sess:\r\n",
    "    sess.run(init)\r\n",
    "    for epoch in range(21):\r\n",
    "        for batch in range (n_batch):\r\n",
    "            batch_xs,batch_ys = mnist.train.next_batch(batch_size)\r\n",
    "            sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})\r\n",
    "        acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})\r\n",
    "        print('Iter' +str(epoch)+',Testing Accuray' +str(acc))\r\n"
   ],
   "outputs": [],
   "metadata": {}
  }
 ],
 "metadata": {
  "orig_nbformat": 4,
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}